<template>
  <div class="dialog_image">
    <dir-tree @SelectNode="handleSelectNode" :ifEdit="false"></dir-tree>
    <div class="toolbar"><el-button type="primary" size="small" @click="dialogShow=true">上传</el-button></div>
    <div class="imgList cl">
      <div v-for="item in sourceList.list" class="imgWrap" @click="handleSelectImg(item)">
        <img :src="item.url" alt="">
        <h4 class="title">{{item.name}}</h4>
        <div v-if="item.id === selected.id" class="mask"><i class="el-icon-check"></i></div>
      </div>
    </div>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page.sync="page"
        :page-size.sync="size"
        layout="total, prev, pager, next, jumper"
        :total="sourceList.page.total"
        @current-change="initComponent()">
      </el-pagination>
    </div>
    <!-- 上传弹层 -->
    <el-dialog title="新建图片" :modal="false" :visible.sync="dialogShow" custom-class="dialog_upload" @open="initUpload">
      <el-row>
        <div class="field-tit">内容性质:</div>
        <div class="field-bd">
          <el-select v-model="contentType">
            <el-option v-for="item,n in attrs" :label="item.name" :value="item.id" :key="n.toString()"></el-option>
          </el-select>
        </div>
      </el-row>
      <el-row>
        <div class="field-tit">选择文件:</div>
        <div class="field-bd">
          <el-upload ref="upload"
            class="upload"
            :action="baseUrl + '/content/source/upload/image'"
            :data="params"
            :headers="headers"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="handleBeforeUpload"
            :auto-upload="false"
            :file-list="fileList">
            <el-input placeholder="请选择文件" class="input-upload">
              <el-button slot="append">浏览</el-button>
            </el-input>
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png文件</div>
          </el-upload>
        </div>
      </el-row>
      <div slot="footer">
        <el-button @click="dialogShow=false;">关闭</el-button>
        <el-button type="primary" @click="handleSaveImg">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {mapState, mapActions, mapMutations} from 'vuex'
  import dirTree from '@/components/common/content/dirTree'
  import env from '@/config/env'
  export default {
    components: {dirTree},
    data () {
      return {
        baseUrl: env.baseUrl,
        contentType: null,
        fileList: [],
        page: 1,
        size: 10,
        dialogShow: false
      }
    },
    mounted () {
      const that = this
      this.$bus.$off('reloadSource')
      this.$bus.$on('reloadSource', function () {
        that.initComponent()
      })
      this.$bus.$on('reloadImage', function () {
        that.initComponent()
      })
    },
    computed: {
      ...mapState({
        curDir: state => state.sourceManage.currentDir,
        sourceList: state => state.sourceManage.imgList,
        selected: state => state.sourceManage.selected,
        attrs: state => state.contentManage.contentType,
        currentDir: state => state.sourceManage.currentDir
      }),
      // 文件上传附加的头部
      headers () {
        return {
          UBToken: localStorage.getItem('UBToken')
        }
      },
      // 文件上传附加的参数
      params () {
        return {
          contentType: this.contentType,
          pid: this.currentDir
        }
      },
      token () {
        return localStorage.getItem('UBToken')
      }
    },
    methods: {
      ...mapActions(['getSourceList']),
      ...mapMutations(['SELECT_SOURCE']),
      // 初始化组件
      async initComponent () {
        await this.getSourceList({
          type: 2,
          pid: this.curDir,
          size: this.size,
          page: this.page
        })
      },
      // 选择文件夹
      async handleSelectNode () {
        await this.getSourceList({
          type: 2,
          pid: this.curDir,
          size: this.size,
          page: this.page
        })
      },
      // 选中图片
      handleSelectImg (image) {
        this.SELECT_SOURCE(image)
      },
      // 上传成功回调
      handleSuccess (res, file, fileList) {
        this.isSave = false
        this.dialogShow = false
        this.$bus.$emit('reloadSource')
        if (res.code !== 1) {
          this.$message({
            type: 'warning',
            message: res.msgZ
          })
          fileList.forEach((item, n) => {
            if (item === file) {
              fileList.splice(n, 1)
            }
          })
        }
      },
      // 上传失败回调
      handleError (res) {
        this.isSave = false
        this.$message.warning(res.msgZ)
      },
      // 上传前的检验
      handleBeforeUpload (file) {
        const allowTypes = ['image/jpg', 'image/jpeg', 'image/png']
        if (allowTypes.indexOf(file.type) === -1) {
          this.$message.warning('格式不支持')
          return false
        }
        this.isSave = true
      },
      // 保存
      handleSaveImg () {
        if (!this.contentType) {
          this.$message.warning('请选择内容性质')
          return
        }
        if (!this.$refs.upload.uploadFiles.length) {
          this.$message.warning('请选择图片内容')
          return
        }
        this.$refs.upload.submit()
      },
      // 初始化上传
      initUpload () {
        this.contentType = ''
        this.$refs.upload && this.$refs.upload.clearFiles()
      }
    }
  }
</script>
<style lang="scss">
  .dialog_image{
    .imgList{margin-left:215px;}
    .toolbar{margin:0 0 5px 215px;padding-bottom:5px;border-bottom:1px solid #e0e6ed}
    .imgWrap{
      position:relative;float:left;margin-right:10px;margin-bottom:15px;width:117px;border:1px solid #e7e7eb;cursor:pointer;
      img{width:117px;height:117px;vertical-align:top;}
      .title{height:28px;line-height:28px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
      .mask{position:absolute;top:0;left:0;right:0;bottom:28px;background:rgba(0,0,0,.7);color:#fff;font-size:30px;text-align:center;line-height:117px;}
    }
    .dialog_upload{
      &{width:500px !important;}
      .el-row{margin-bottom:10px;}
    }
    .el-dialog__body{
      .el-button{
        margin-top: 0;
      }
    }
  }
</style>
